package org.micode.common.remote;

import org.micode.common.enums.ResultEnum;
import org.micode.common.exception.RemoteServiceException;
import org.micode.common.domain.ApiResult;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 服务类,基本方法
 */
@Slf4j
public class ApiHelper {

	public static <T, R> R invoke(Function<T, ApiResult<R>> method, T t) {
		ApiResult<R> ret = method.apply(t);
		if (ResultEnum.SUCCESS.getCode() == ret.getCode()) {
			return ret.getData();
		} else {
			log.error("Invoke API failed, code={}, msg={}, args={}",
					ret.getCode(), ret.getMsg(), t);
			throw new RemoteServiceException("code=" + ret.getCode() + ", msg=" + ret.getMsg());
		}
	}

	public static <R> R invoke(Supplier<ApiResult<R>> method) {
		ApiResult<R> ret = method.get();
		if (ResultEnum.SUCCESS.getCode() == ret.getCode()) {
			return ret.getData();
		} else {
			log.error("Invoke API failed, code={}, msg={}",
					ret.getCode(), ret.getMsg());
			throw new RemoteServiceException("code=" + ret.getCode()
					+ ", msg=" + ret.getMsg());
		}
	}

	public static <T> void accept(Consumer<T> method, T t) {
		method.accept(t);
	}

}
